<?php
function list_table($crud, $phpFile, $headerTitles, $tableName){
	
	$table = $crud->getAll();
//	echo list_table_raw_string($table, $phpFile, $headerTitles, $tableName);
	list_table_raw($table, $phpFile, $headerTitles, $tableName);
}

function isSessionActive(){
	if (!isset($_SESSION['user_mail'])){
		return 0;
	} 
	return 1;
}


function startToodledoConnection(){
	$users = new Users(con());
	$tid = $users->getToodledoId();
	if (isToodledoEnabled() > 0) {
		$tid = $tid[0][0];
		$tpass = $users->getToodledoPass();
		$t = new Toodledo($tid, $tpass);
	}
}

function getToodledoConnection(){
	$users = new Users(con());
	$tid = $users->getToodledoId();
	$tid = $tid[0][0];
	$tpass = $users->getToodledoPass();
	$t = new Toodledo($tid, $tpass);
	return $t;
}

function isToodledoEnabled(){
	$users = new Users(con());
	$tid = $users->getToodledoId();
	if (count($tid) > 0) {
		if (strlen($tid[0][0]) >1){
			return 1;			
		}
	}
	return 0;
}

function getRyNyTyFolderc($t){
	$folders = $t->getFolders();
	foreach ($folders->folders->folder as $folder) {
		if (strcmp("rynyty", $folder) == 0){
			return $folder["id"];
		}
	}
	return -1;	
}

function getTasks($t, $folder_id){
	if($folder_id == -1){
		$t->addFolder(array(
		'title' => 'rynyty'
		));
		$folder_id = (string)$response->added;
	}
	$tasks = $t->getTasks(array(
	'folder' => "$folder_id"
	));
	return $tasks->tasks;
}

function addTask($taskName, $folder_id, $t){
	$folders = $t->getFolders();
	$tasks = $t->addTask(array(
	'folder' => "$folder_id",
	'title' => "$taskName"
	));
}

function removeTask($t, $folder_id, $id){
	$folders = $t->getFolders();
	$tasks = $t->deleteTask(array(
	'id' => "$id",
	));
}
function removeAllTasks($t, $folder_id){
	$tasks = getTasks($t, $folder_id);
//	echo "removing: ";
	foreach ($tasks->task as $task) {
//		echo "$task->id <br>";
		$t->deleteTask(array(
		'id' => "$task->id",
		));
	}
}

function toodledoSyncPhp(){
	if (isToodledoEnabled() == 0){
		return;
	}
	$slist = new Shoplist(con());
	$allTodos = $slist->getAll();
	$t = getToodledoConnection();
	$folder_id = getRyNyTyFolderc($t);
	removeAllTasks($t, $folder_id);
	foreach ($allTodos as $taskLine) {
		addTask($taskLine[2]." - ".$taskLine[1], $folder_id, $t);
	}
}

function list_table_raw($table, $phpFile, $headerTitles, $tableName){
	echo '<p> ', $tableName , '</p>';
	echo '<table>';
	echo '<tr>';
	foreach($headerTitles as $title){
		echo '<td class="bold">';
		echo $title;
		echo '</td>';
	}
	echo '</tr>';
	foreach($table as $line){
		echo '<tr>';
		foreach($line as $column){
			echo '<td>';
			echo $column;
			echo '</td>';
		}
		echo '<td>';
		if (strlen($phpFile) > 2){
			echo '<form action="'.$phpFile.'" method="post">';
			echo '<input class="table-submit remove-button" type="submit" value="изтрий" name="Remove">';
			echo '<input type="hidden" name="id" value='.$line[0].'>';
			echo '</form>';
		}
		echo '</td>';
		echo '</tr>';
	}
	echo '</table>';
}


function loadDB() {
	if (!isset($GLOBALS['connection'])){
		$GLOBALS['connection'] = loadDbConnection();
		mysql_query('SET NAMES utf8');
		mysql_query('set lc_time_names bg_BG');
	}
}

function con(){
	loadDB();
	return $GLOBALS['connection'];
}

function generateCombo($elements, $phpRedirect, $name){
	echo '<select name='.$name.' id="combo">';
	foreach($elements as $element){
		echo '<option value="'. $element[0] .'">'. $element[0] .'</option>';
	}
	echo '</select>';
	if (isset($phpRedirect)){
		echo '<a class="link-do-combo" href="'.$phpRedirect.'">edit</a>';	
	}
	
}

function generateComboComplex($elements, $phpRedirect, $name){
	echo '<select name='.$name.' id='.$name.'>';
	foreach($elements as $element){
		echo '<option value="'. $element[0] .'">'. $element[1] .'</option>';
	}
	echo '</select>';
	if (isset($phpRedirect)){
		echo '<a class="link-do-combo" href="'.$phpRedirect.'">edit</a>';	
	}
	
}


function backAction(){
//	if (isset($_SESSION["P"])) {
//		echo '<a href = "'.$_SESSION["P"].'"> Назад </a> <br>';
//	}
	echo '<a href = "generalProduct.php"> продукти </a> <br>';
}

function pre_dump($var){
	echo "<pre>";
	var_dump($var);
	echo "</pre>";
		
}

function generateSecurityQuestion(){
	$first = rand(0, 9);
	$second = rand(0,9);
	$third = rand(0,9);
	$operation1 = rand(0,2);
	$operation2 = rand(0,2);
	$result['txt'] = getCifra($first).''.getOperation($operation1).''.getCifra($second).''.getOperation($operation2).''.getCifra($third);
	$tmp = $first.''.getOperation($operation1).''.$second.''.getOperation($operation2).''.$third;
	eval(" \$result['r'] = $tmp;");
	return $result;
}
function getCifra($cifra){
	if ($cifra == 0){
		return ' нула ';
	} else if ($cifra == 1){
		return ' едно ';
	} else if ($cifra == 2){
		return ' две ';
	} else if ($cifra == 3){
		return ' три ';
	} else if ($cifra == 4){
		return ' четири ';
	} else if ($cifra == 5){
		return ' пет ';
	} else if ($cifra == 6){
		return ' шест ';
	} else if ($cifra == 7){
		return ' седем ';
	} else if ($cifra == 8){
		return ' осем ';
	} else if ($cifra == 9){
		return ' девет ';
	}
}

function getOperation($op){
if ($op == 0){
		return '+';
	} else if ($op == 1){
		return '-';
	} else if ($op == 2){
		return '*';
	}
}

function loginCheck(){
	if(!isBrowserSupported()){
		header("Location: supportedBrowsers.php");
	}
	if (isset($_SESSION['user'])){
	  return;
	}
	if(isset($_COOKIE['rynyty'])){
    	if(isset($_COOKIE['rynyty']['usr'])) {
    		if (isValidUser($_COOKIE['rynyty']['usr'],  $_COOKIE['rynyty']['pwd']) == 1){
    			gotoRequestedURL();
    		}
    	}
    } else if (isset($_SESSION['user'])){
    	gotoRequestedURL();
    }
	if (!isset($_SESSION['user'])){
		$_SESSION['rulr'] = $_SERVER['REQUEST_URI'];
    	header("Location: login.php");
	}
}

function isAdmin(){
	if (!isset($_SESSION['user_mail'])){
	} else {
		$users = new Users(con());
		$validUser = $users->getUsers($_SESSION['user_mail']);
		if (count($validUser) != 1){
		} else {
			if (strcasecmp($validUser[0][2], "admin") == 0){
				return;
			}
		}
	}
	header("Location: ../main.php");
}


function isValidUser($user, $pass){
	$users = new Users(con());
	$validUser = $users->getObject($user, $pass);
	if (count($validUser) != 1){
		return 0;
	} else {
		if (strcasecmp($validUser[0][2], "new") == 0){
			return -1;
		}
		$_SESSION['user'] = $validUser[0][3];
		$_SESSION['user_id'] = $validUser[0][4];
		setGroupId($validUser[0][4]);
		$_SESSION['user_mail'] = $validUser[0][0];
		return 1;
	}
} 

function checkUser($user, $pass){
	$users = new Users(con());
	$validUser = $users->getObject($user, md5($pass));
	if (count($validUser) != 1){
		return 0;
	} else {
		if (strcasecmp($validUser[0][2], "new") == 0){
			return -1;
		}
		return 1;
	}
} 

function checkUserPass($pass){
	$users = new Users(con());
	$validUser = $users->getObject($_SESSION['user_mail'], md5($pass));
	if (count($validUser) != 1){
		return 0;
	} else {
		if (strcasecmp($validUser[0][2], "new") == 0){
			return -1;
		}
		return 1;
	}
} 

function changePass($oldpass, $newpass){
	$users = new Users(con());
	$validUser = $users->changePass(md5($oldpass), md5($newpass));
}

function changeToodledoId($toodledo_id, $tpass){
	$users = new Users(con());
	$validUser = $users->changeToodledoId($toodledo_id);
	
	if (count($tpass) > 0){
		$validUser = $users->saveToodledoPass(md5($tpass));
	}
}

function setGroupId($userid){
	$groups = new Groups(con());
	$group = $groups->getGroup($userid);
	if (count($group) > 0){
		$_SESSION['group_id'] = $group[0][0]; 
	} else {
		$_SESSION['group_id'] = -1;
	} 
}

function getPost($index){
	if (!isset($_POST[$index])){
		return "";
	}
	return $_POST[$index];
}
function escape_string($str) {
	if ($str !== null) {
		$str = str_replace(array('\\','\''),array('\\\\','\\\''),$str);
//		$str = "'".$str."'";
	} else {
		$str = "null";
	}
	return $str;
}
function gotoRequestedURL(){
	if (isset($_SESSION['rulr'])){
		$temp = $_SESSION['rulr'];
		unset($_SESSION['rulr']);
		header("Location: $temp");
	} else {
		redirectToLastPage();
	}
}



function isBrowserSupported(){
    if (isset($_SERVER['HTTP_USER_AGENT']) && 
    (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') != false))
        return false;
    else
        return true;
}

function redirectToLastPage(){
	if(isset($_COOKIE['rynyty'])){
    	if(isset($_COOKIE['rynyty']['lastpage'])){
    		$temp =  $_COOKIE['rynyty']['lastpage'];
    		header("Location: $temp");
    	} else {
    		header("Location: main.php");
    	}
	} else {
		header("Location: main.php");
	}
}
function transformResults($mresults, $tokens){
	$results = array();
		$num=mysql_numrows($mresults);
		$i=0;
		while ($i < $num) {
			$j=0;
			foreach ($tokens as $token){
				$results[$i][$j] = mysql_result($mresults,$i,$token);
				$j++;	
			}
			$i++;
		}
		return $results;
	}

?>